import { createRequest } from '../index'
import { McRequest } from '../McRequest'

const request = createRequest({ baseURL: '' })

interface ITestItem {
  name: string
  fn: () => Promise<any>
}

const testRequestList: ITestItem[] = [
  /**基础请求测试 */
  { name: 'get', fn: () => request.get('/get/listData') },
  { name: 'post', fn: () => request.post('/post/cityList', { name: 2 }) },
  {
    name: '文件上传',
    fn: async () => {
      const file = new File(['test txt1', 'test txt2'], 'testFileName')
      const formData = new FormData()
      formData.append('file', file)
      return request.postFormData('/upload/file', formData)
    }
  },
  { name: '请求失败', fn: () => request.get('/fail') },
  { name: '响应异常', fn: () => request.get('/resError') },
  { name: '响应超时', fn: () => request.get('/resTimeout') },
  { name: '404接口', fn: () => request.get('/xxx') },
  {
    name: '返回的对象键不确定',
    fn: async () => {
      const res: Response = await request.get('/resRandom', {}, { isOrigina: true })
      return res.json()
    }
  },
  {
    name: '返回文件流',
    fn: async () => {
      const res: Response = await request.get('/file-stream', {}, { isOrigina: true })
      return res.blob()
    }
  },
  /**中间件功能测试 */
  { name: '接口缓存-1-列表数据', fn: () => request.get('/api/listData', { count: 3 }, { dataCache: true }) },
  { name: '接口缓存-2-列表数据', fn: () => request.get('/api/listData', { count: 5 }, { dataCache: true }) },
  { name: '接口防抖-评论列表', fn: () => request.get('/api/commentList', {}, { debounce: true }) },
  /**模拟业务接口测试 */
  { name: '模拟登录', fn: () => request.postJson('/user/login', { username: 'admin', password: 321321 }) },
  {
    name: '模拟页面切换时取消未完成的所有请求',
    fn: async () => {
      // 发出10个请求
      for (let i = 0; i < 10; i++) {
        const time = ~~(Math.random() * 5000)
        request.get('/resTimeout', { time }).then((res) => {
          console.log(`第 ${i + 1} 个请求已完成，返回值为: ${res}`)
        })
      }

      setTimeout(() => {
        console.log(McRequest.abortCtrBucket, '-->>> McRequest.abortCtrBucket')
        console.log(`2 秒后取消所有未完成的[ ${McRequest.abortCtrBucket.size} ]个请求`)
        McRequest.abortCtrBucket.forEach((item) => {
          item.controller.abort()
          console.log(`[ ${item.url} ] 已被取消`)
        })
      }, 2000)
    }
  }
]

const apiBox = document.getElementById('apiBox')!
for (const item of testRequestList) {
  const divDom = document.createElement('div')
  divDom.className = 'item_api_box'
  divDom.setAttribute('data-name', item.name)
  divDom.innerHTML = `
  <button class="but">send</button>
  <span class="title_box"> ${item.name} </span>
  `
  divDom.onclick = function () {
    item
      .fn()
      .then((res: any) => {
        console.log(res, item.name)
      })
      .catch((error) => {
        console.error(error, item.name, 'error')
      })
  }
  apiBox.append(divDom)
}

const sleep = (t = 0) => new Promise((a) => setTimeout(a, t))
// 自动测试
const autoTest = document.getElementById('autoTest')!
autoTest.onclick = async function () {
  for (const item of testRequestList) {
    try {
      await item.fn()
    } catch (error) {
      console.error(error)
    }
    await sleep(300)
    console.log(item.name)
    const curDom = document.querySelector(`.item_api_box[data-name='${item.name}']`)!
    curDom.setAttribute('data-test', 'end')
  }
}
